<template>
  <div style="width:100%;">
    <el-row :gutter="20" class="wrapperSon">
      <span>订单排序: </span>
      <el-select
        v-model="queryConditions.sortMethod"
        placeholder="请选择排序"
        style="width:13%;"
        @change="handleSortMethdSelChange"
      >
        <el-option
          v-for="itm in this.ddSortMethods"
          :label="itm.label"
          :value="itm.value"
          :key="itm.value"
        >
        </el-option>
      </el-select>
      <span>瓶颈工序: </span>
      <el-select
        v-model="queryConditions.bottleProcedureId"
        placeholder="请选择瓶颈工序"
        style="width:13%;"
        @change="handleBottleneckChange"
      >
        <el-option
          v-for="itm in this.ddBottleneckProcedures"
          :label="itm.label"
          :value="itm.value"
          :key="itm.value"
        >
        </el-option>
      </el-select>
    </el-row>
    <el-row :gutter="20" type="flex" justify="start">
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        @row-click="rowClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column align="center" label="订单编号" width="95">
          <template slot-scope="scope">
            {{ scope.row.orderNo }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="产品编号" width="95">
          <template slot-scope="scope">
            {{ scope.row.productNo }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="产品名称" width="95">
          <template slot-scope="scope">
            {{ scope.row.productName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="产线编号" width="95">
          <template slot-scope="scope">
            {{ scope.row.produceLineNo }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="产线名称" width="95">
          <template slot-scope="scope">
            {{ scope.row.produceLineName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="批次" width="95">
          <template slot-scope="scope">
            {{ scope.row.batch }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="客户需求量" width="95">
          <template slot-scope="scope">
            {{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="已生产数量" width="95">
          <template slot-scope="scope">
            {{ scope.row.producedAmount }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="未生产数量" width="95">
          <template slot-scope="scope">
            {{ scope.row.planAmount }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="交货时间"
          width="95"
          :sortable="true"
          :sort-method="sortByDeliverydate"
        >
          <template slot-scope="scope">
            {{ scope.row.deliveryDate }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="计划开始时间" width="95">
          <template slot-scope="scope">
            {{ scope.row.planProduceStartDate }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="计划结束时间" width="95">
          <template slot-scope="scope">
            {{ scope.row.planProduceEndDate }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="工期" width="95">
          <template slot-scope="scope">
            {{ scope.row.duration }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="最晚生产开始时间" width="95">
          <template slot-scope="scope">
            {{ scope.row.latestProduceStartDate }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="最晚生产结束时间" width="95">
          <template slot-scope="scope">
            {{ scope.row.latestProduceEndDate }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="排产状态" width="95">
          <template slot-scope="scope">
            {{ scope.row.scheduleState | statusFilter }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="自由时差" width="95">
          <template slot-scope="scope">
            {{ scope.row.freeFloat }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="优先级"
          width="95"
          :sortable="true"
          :sort-method="sortByPriority"
        >
          <template slot-scope="scope">
            {{ scope.row.priority }}
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        :page-sizes="listQuery.pageSizes"
        @pagination="fetchData"
      />
    </el-row>
    <el-row class="app-container">
      <reportchart
        :input="{ ...tempSon }"
        v-show="parseInt(this.staticType) === 1"
      ></reportchart>
      <produceprogresschart
        :input="{ ...tempSon }"
        v-show="parseInt(this.staticType) === 2"
      ></produceprogresschart>
    </el-row>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {
  getAll,
  getList,
  create,
  update,
  deleteBatch,
  getBottleneckProcedure,
  getScheduledProduceOrderProductPlans
} from "@/api/produce/schedulePlan/ProduceOrderProductPlanApi";
import moment from "moment";
import reportchart from "@/views/produce/schedulePlan/statics/reportChart";
import produceprogresschart from "@/views/produce/schedulePlan/statics/produceProgressChart";

/**此界面全为前端排序！！！ */
export default {
  name: "schedulemonthdetailson",
  components: { Pagination, reportchart, produceprogresschart },
  filters: {
    statusFilter(status) {
      const statusMap = {
        UNSCHEDULE: "未排产",
        FORWARD_SCHEDULED: "正排完成",
        FORMARD_EXCEEDED: "正排超时",
        BACKWARD_SCHEDULED: "倒排完成",
        BACKMARD_EXCEEDED: "倒排超时"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      lstOrign: [], //原始数据
      list: [], //用于前端过滤
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentSaleOrderMstTypeId: 0,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      temp: {
        id: undefined,
        orderNo: "",
        productNo: "",
        productName: "",
        produceProcedureNo: "",
        produceProcedureName: "",
        batch: "",
        totalAmount: "",
        producedAmount: "",
        planAmount: "",
        deliveryDate: "",
        planProduceStartDate: "",
        planProduceEndDate: "",
        duration: 0,
        latestProduceStartDate: "",
        latestProduceEndDate: "",
        scheduleState: 0,
        freeFloat: "",
        priority: 0,
        schedulePeriod: "",
        schedulePeriodType: 0
      },
      //表格變量
      lstSelected: [],
      queryConditions: {
        sortMethod: 0, //订单排序
        scheduleState: 0,
        bottleProcedureId: 0 //瓶颈工序Id
      },
      lstOrders: [],
      dialogProduceLineVisible: false,
      scheduleMethod: 0, //1:正序排产，2:倒序排产
      dialogCRUDVisible: false,
      planSort: 1, //1:按交期排序排产;2:按优先级排序排产

      /**可编辑表格 */
      listSon: [],
      lstSelectedSon: [],
      tempSon: {
        schedulePeriod: "",
        productNo: "",
        orderNo: "",
        schedulePeriodType: 1
      },
      rowIndex: 0, //行的标识,
      ddSortMethods: [
        { label: "请选择", value: 0 },
        { label: "交期", value: 1 },
        { label: "优先级", value: 2 }
      ],
      ddBottleneckProcedures: [], //去重后的瓶颈工序数据
      ddBottleneckProceduresOrign: [], //全量瓶颈工序数据
      currentProduceLineId: 0,
      totalPlanAmount: 0, //计划生产总量
      staticType: 0 //统计报表类型
    };
  },
  props: {
    produceLineId: 0,
    monthSel: ""
  },
  watch: {
    produceLineId: function(newValue, oldValue) {
      if (oldValue != newValue) {
        this.currentProduceLineId = newValue;
        this.fetchData();
      }
    },
    monthSel: function(newValue, oldValue) {
      if (oldValue != newValue) {
        this.tempSon.schedulePeriod = newValue;
        this.fetchData();
      }
    },
    $route: "resolveStaticType"
  },
  computed: {},
  created() {
    //解析统计类型
    this.resolveStaticType();
    //获取瓶颈工序
    let param = {
      produceLineId: 0,
      sourceType: 0
    };
    this.getBottleneckProcedure(param);
    this.fetchData();
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
      const type = this.list.find(v => v.therbligsNo === val.therbligsNo);
      if (type != null) {
        this.currentSaleOrderMstTypeId = type.id;
      }
    },
    fetchData() {
      let params = {
        page: this.listQuery.page,
        size: this.listQuery.limit,
        produceLineId: this.currentProduceLineId,
        planPeriod: this.monthSel
      };
      // params = Object.assign(params, this.queryConditions);
      return getScheduledProduceOrderProductPlans(params).then(response => {
        this.list = response.data.records;
        this.lstOrign = response.data.records;
        console.log(this.list);
        this.total = response.data.total;
        this.listLoading = false;
        this.list.forEach(v => {
          this.totalPlanAmount += v.planAmount;
        });
        this.$emit("changeTotalPlanAmount", this.totalPlanAmount);
      });
    },
    rowClick(row, column, event) {
      this.currentSaleOrderMstTypeId = row.id;
      this.tempSon.orderNo = row.orderNo;
      this.tempSon.productNo = row.productNo;
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        orderNo: "",
        productNo: "",
        productName: "",
        produceProcedureNo: "",
        produceProcedureName: "",
        batch: "",
        totalAmount: "",
        producedAmount: "",
        planAmount: "",
        deliveryDate: "",
        planProduceStartDate: "",
        planProduceEndDate: "",
        duration: 0,
        latestProduceStartDate: "",
        latestProduceEndDate: "",
        scheduleState: "",
        freeFloat: "",
        priority: 0,
        schedulePeriod: "",
        schedulePeriodType: 0
      };
    },
    handleMainTypeChange(val) {
      this.temp.saleOrderMstTypeId = val;
      this.temp = { ...this.temp };
    },
    querySearch(queryString, cb) {
      let orders = this.lstOrders;
      let results = queryString
        ? this.lstOrders.filter(this.createFilter(queryString))
        : this.lstOrders;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return p => {
        return p.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    /**
     * 子组件关闭时通知父组件
     */
    hideDlg(e) {
      this.dialogFormVisible = e;
    },

    getBottleneckProcedure(params) {
      this.ddBottleneckProcedures.push({
        label: "请选择",
        value: 0,
        produceLineId: 0
      });
      getBottleneckProcedure(params).then(response => {
        if (response.data != null && response.data.length > 0) {
          response.data.forEach(v => {
            this.ddBottleneckProceduresOrign.push({
              label: v.procedureName,
              value: v.id,
              produceLineId: v.produceLineId
            });
            let idx = this.ddBottleneckProcedures.findIndex(
              o => o.value == v.id
            );
            if (idx < 0) {
              this.ddBottleneckProcedures.push({
                label: v.procedureName,
                value: v.id,
                produceLineId: v.produceLineId
              });
            }
          });
        }
      });
    },
    /**表格排序方法 */
    sortByDeliverydate(obj1, obj2) {
      return moment(obj1.deliveryDate, "YYYY-MM-DD HH:mm:ss").diff(
        moment(obj2.deliveryDate, "YYYY-MM-DD HH:mm:ss"),
        "seconds"
      );
    },
    /**表格排序方法 */
    sortByPriority(obj1, obj2) {
      return obj2.priority - obj1.priority;
    },
    handleBottleneckChange(val) {
      if (val == 0) {
        this.list = this.lstOrign;
      } else {
        //先找到产线IDS
        let produceLineIds = this.ddBottleneckProceduresOrign.filter(
          o => o.value == val
        );
        if (produceLineIds != null && produceLineIds.length > 0) {
          this.list = this.lstOrign.filter(
            o =>
              produceLineIds.findIndex(
                v => v.produceLineId == o.produceLineId
              ) > -1
          );
        }
      }
    },
    //排序方法改变事件
    handleSortMethdSelChange(e) {
      if (e == 1 || e == 0) {
        this.planSort = 1;
        this.list.sort(this.sortByDeliverydate);
      } else {
        this.list.sort(function(obj1, obj2) {
          return obj1.priority - obj2.priority;
        });
        this.planSort = 2;
      }
    },
    resolveStaticType() {
      let p = this.$route.path.split("/");
      if (p != null && p.length > 0) {
        let num = parseInt(p[p.length - 1]);
        if (num != null) {
          this.staticType = num;
          return;
        }
      }
      this.staticType = 1;
    }
  }
};
</script>
<style scoped>
.el-row {
  padding: 10px;
  font-size: 13px;
}
.item1 {
  margin-top: 20px;
}
.wrapperSon {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.app-container {
  padding: 0;
}

/**edit table css */
.tb-edit .el-input {
  display: none;
}
.tb-edit .current-row .el-input {
  display: block;
}
.tb-edit .current-row .el-input + span {
  display: none;
}
.el-table-add-row {
  margin-top: 10px;
  width: 100%;
  height: 34px;
  border: 1px dashed #c1c1cd;
  border-radius: 3px;
  cursor: pointer;
  justify-content: center;
  display: flex;
  line-height: 34px;
}
.main_container {
  width: 100%;
  height: 200px;
  overflow: hidden;
}
</style>
